<?php
declare (strict_types=1);

namespace app\mall\model;

use app\mall\enum\YesNoEnum;
use app\mall\model\traits\TreeTrait;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Model;
use think\model\relation\HasMany;

/**
 * @mixin Model
 */
class MallCate extends MallBase
{
    use TreeTrait;

    public function getChildCountAttr($value, $data)
    {
        return static::where('parent_id', $data['id'])->count();
    }

    public function getHasChildAttr($value, $data)
    {
        return !!$this->getChildCountAttr($value, $data);
    }

    public function getIsMenuTextAttr($key, $data)
    {
        return (new YesNoEnum($data['is_menu']))->getZhName();
    }

    /**
     * 获取商品
     * @return HasMany
     */
    public function cateAttrs(): HasMany
    {
        return $this->hasMany(MallCateAttr::class, 'id', 'cate_id');
    }

    public static function getTree()
    {
        try {
            $list = static::field(['id', 'parent_id', 'title'])->select();
        } catch (DataNotFoundException|ModelNotFoundException|DbException $e) {
            return [];
        }
        return static::buildTree($list, 0,'id', 'title');
    }
}